package com.cheng.cms.aspect;

import com.cheng.cms.annotation.Log;
import com.cheng.cms.utils.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 *  日志记录访问数据操作处理
 *
 *  @author chenglong
 */
@Aspect
@Component
public class LogAspect {

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    // 配置织入点
    @Pointcut("@annotation(com.cheng.cms.annotation.Log)")
    public void logPointCut()
    {
    }

    /**
     * 处理完请求后处理
     * @param joinPoint
     * @param jsonResult
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
    {
        handleLog(joinPoint, null, jsonResult);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult)
    {

        // 获得注解
        Log controllerLog = null;
        try {
            controllerLog = getAnnotationLog(joinPoint);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (controllerLog == null)
            {
                return;
            }else {
            //获取当前用户
            String user = (String) SecurityUtils.getSubject().getPrincipal();
            System.out.println("用户:"+user+"在"+ DateUtil.getCurrentDate()+"请求调用"+controllerLog.type());
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(Log.class);
        }
        return null;
    }


}
